﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace ResxLocalizationEditor {
	class EditorTextBox : TextBox {

		bool _editingMode = false;

		public bool EditingMode {
			get {
				return _editingMode;
			}
			private set {
				if (_editingMode != value) {
					this.BackColor = (value) ? Color.Khaki : SystemColors.Window;
				}
				
				_editingMode = value;
			}
		}

		public override string Text {
			get {
				return base.Text;
			}
			set {
				base.Text = value;

				EditingMode = false;
			}
		}

		bool _prevKeyHasControl = false;

		protected override void OnKeyDown(KeyEventArgs e) {
			if (e.Alt) {
				if (e.KeyCode == Keys.Up)
					OnMoveCommandIssued(Direction.Up);
				else if (e.KeyCode == Keys.Down)
					OnMoveCommandIssued(Direction.Down);
				else if (e.KeyCode == Keys.Right)
					OnMoveCommandIssued(Direction.Right);
				else if (e.KeyCode == Keys.Left)
					OnMoveCommandIssued(Direction.Left);
			}

			_prevKeyHasControl = e.Control;

			base.OnKeyDown(e);
		}

		protected override void OnKeyPress(KeyPressEventArgs e) {
			if (_prevKeyHasControl && (e.KeyChar == '\n' || e.KeyChar == '\r')) {
				OnEditingCompleted();
				EditingMode = false;

				e.Handled = true;
			}
			else {
				EditingMode = true;
			}

			base.OnKeyPress(e);
		}

		public event EventHandler EditingCompleted;

		protected virtual void OnEditingCompleted() {
			if (EditingCompleted != null)
				EditingCompleted(this, EventArgs.Empty);
		}

		public event EventHandler<MoveEventArgs> MoveCommandIssued;

		protected virtual void OnMoveCommandIssued(Direction direction) {
			if (MoveCommandIssued != null)
				MoveCommandIssued(this, new MoveEventArgs(direction));
		}

	}

	class MoveEventArgs : EventArgs {

		public MoveEventArgs(Direction direction) {
			MoveDirection = direction;
		}

		public Direction MoveDirection { get; set; }

	}
}
